﻿using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using System.Collections.Generic;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu.Model.Response;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu.Model.Request;
using ZBJF.Warranty.TheThirdPartyInteraction.Sellers.ChiDu;

namespace ZBJF.Warranty.WebApiSite.Filter
{
    /// <summary>
    /// 销售商身份验证过滤器
    /// </summary>
    public class SellerAuthenticationAttribute : ActionFilterAttribute
    {
        /// <summary>
        /// 身份票据 （账号|Md5(密码)）
        /// </summary>
        private readonly string ticketName = "ticket";
        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            InsuranceOrderInfoParam param = new InsuranceOrderInfoParam
            {
                SellerBusinessNo = "itest_null_2018041611111",
                CertificateImageUrl = "http://tadmin.zhongbaojinfu.com.cn/UploadFile/File/2017/11/09/20171109041117.jpg",
                CertificateNO = "362202199632563311",
                CertificateType = 1,
                IMEI = "111111111111114",
                ModelId = 155,
                SellerInsuranceProductsCode = "XSSCP000060",
                Timestamp = 1523872799,
                UserName = "张三100",
                SaleEmployeeId = "334",
                UserPhone = "1520928123"
            };
            var json = JsonConvert.SerializeObject(param);
            EncryptionParamData vali = new EncryptionParamData("zbjf_fjcd78g4fd45f465g4489g48r49");
            vali.SetValue("SellerBusinessNo", param.SellerBusinessNo);
            vali.SetValue("SellerInsuranceProductsCode", param.SellerInsuranceProductsCode);
            vali.SetValue("SaleEmployeeId", param.SaleEmployeeId);
            vali.SetValue("UserName", param.UserName);
            vali.SetValue("UserPhone", param.UserPhone);
            vali.SetValue("CertificateType", param.CertificateType);
            vali.SetValue("CertificateNO", param.CertificateNO);
            vali.SetValue("IMEI", param.IMEI);
            vali.SetValue("ModelId", param.ModelId);
            vali.SetValue("CertificateImageUrl", param.CertificateImageUrl);
            vali.SetValue("Timestamp", param.Timestamp);
            string sign = vali.MakeSign();

            EncryptionParamData vali1 = new EncryptionParamData("zbjf_fjcd78g4fd45f465g4489g48r49");
            vali1.SetValue("SellerBusinessNo", "itest_null_20180409142816379");
            vali1.SetValue("ThirdOrderNO", "H10104P08490220181591013");
            vali1.SetValue("Timestamp", 1523872799);
            string sign1 = vali1.MakeSign();


            ResultObject<string> resultObject = new ResultObject<string>();
            resultObject.Result = true;
            resultObject.StatusCode = StatusCodeEnum.Unauthorized;
            resultObject.Message = "未授权标识！";
            var ticket = HttpContext.Current.Request.Headers.Get(ticketName);
            try
            {
                //验证票据不为空
                if (string.IsNullOrEmpty(ticket))
                {
                    LogHelper.WriteLog("验证第三方平台身份信息(OnActionExecuting)_票据为空;ticket:" + ticket, LogType.tag);
                    var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
                    response.Content = new StringContent(JsonConvert.SerializeObject(resultObject), Encoding.UTF8, "application/json");
                    return;
                }
                //验证票据格式
                string[] info = ticket.Trim().Split('|');
                if (info == null || info.Length != 2)
                {
                    LogHelper.WriteLog("验证第三方平台身份信息(OnActionExecuting)_票据格式不正确;ticket:" + ticket, LogType.tag);
                    var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
                    response.Content = new StringContent(JsonConvert.SerializeObject(resultObject), Encoding.UTF8, "application/json");
                    return;
                }

                string account = info[0];
                string password = info[1];
                string sellerPassword = ServiceFactory.SellersServiceInstance.GetSellerPassword(account);
                //验证密码是否正确
                if (sellerPassword.ToMD5Encrypt32() != password)
                {
                    LogHelper.WriteLog("验证第三方平台身份信息(OnActionExecuting)_密码错误;ticket:" + ticket, LogType.tag);
                    var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
                    response.Content = new StringContent(JsonConvert.SerializeObject(resultObject), Encoding.UTF8, "application/json");
                    return;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("验证第三方平台身份信息(OnActionExecuting)_异常;ticket:" + ticket + ";\r\n异常信息：" + ex.ToString(), LogType.error);
                var response = filterContext.Response = filterContext.Response ?? new HttpResponseMessage();
                response.Content = new StringContent(JsonConvert.SerializeObject(resultObject), Encoding.UTF8, "application/json");
                return;
            }

            base.OnActionExecuting(filterContext);
        }
    }
}